package com.xtaller.core.helper;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by Administrator on 2017/5/27.
 * 时间格式化类
 */
public class TimeHelper {
    /**
     * 获取当前服务器时间Date
     * */
    private static Date now(){
        return new Date();
    }

    /**
     * 获取当前时间戳
     * */
    public static long getTimestamp(){
        return System.currentTimeMillis()/1000;
    }

    /**
     * 格式化当前时间
     * @param format
     *      时间格式 例如：yyyy-MM-dd
     * */
    public static String formatNow(String format){
        return new SimpleDateFormat(format)
                .format(now());
    }
    /**
     * 格式化当前时间
     * @param date
     *      时间
     * @param format
     *      时间格式 例如：yyyy-MM-dd
     * */
    public static String formatDate(Date date,String format){
        return new SimpleDateFormat(format)
                .format(date);
    }

    /**
     * 获得所在星期的第一天
     */
    public static Date getFirstDateByWeek(Date date) {

        Calendar now = Calendar.getInstance();
        now.setTime(date);
        int today = now.get(Calendar.DAY_OF_WEEK);
        int first_day_of_week = now.get(Calendar.DATE) + 2 - today; // 星期一
        now.set(now.DATE, first_day_of_week);
        return now.getTime();
    }

    /**
     * 获得所在星期的最后一天
     */
    public static Date getLastDateByWeek() {
        Calendar now = Calendar.getInstance();
        now.setTime(now());
        int today = now.get(Calendar.DAY_OF_WEEK);
        int first_day_of_week = now.get(Calendar.DATE) + 2 - today; // 星期一
        int last_day_of_week = first_day_of_week + 6; // 星期日
        now.set(now.DATE, last_day_of_week);
        return now.getTime();
    }

    /**
     * 获得所在月份的最后一天
     */
    public static Date getLastDateByMonth() {
        Calendar now = Calendar.getInstance();
        now.setTime(now());
        now.set(Calendar.MONTH, now.get(Calendar.MONTH) + 1);
        now.set(Calendar.DATE, 1);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - 1);
        now.set(Calendar.HOUR, 11);
        now.set(Calendar.MINUTE, 59);
        now.set(Calendar.SECOND, 59);
        return now.getTime();
    }

    /**
     * 获得所在月份的第一天
     */
    public static Date getFirstDateByMonth() {
        Calendar now = Calendar.getInstance();
        now.setTime(now());
        now.set(Calendar.DATE, 0);
        now.set(Calendar.HOUR, 12);
        now.set(Calendar.MINUTE, 0);
        now.set(Calendar.SECOND, 0);
        return now.getTime();
    }
}
